<?php
/**
 * Created by PhpStorm.
 * User: Earl
 * Date: 2016/10/18
 * Time: 11:29
 */
namespace Redbag\Model;
//require 'autoload.php';
//use JPush\Client as JPush;
use Admin\Controller\CommonController;
use Think\Model;
use Trade\Model\TradeModel;
use Message\Core\Openfire;
use User\Model\UserModel;
use Push\Controller\ApiController as Push;
//use Common\Tools\Pinyin;
class RedbagModel extends Model
{
    protected $tableName = 'redbag';
    protected $pk = 'id';
    protected $tablePrefix;

    private $map = array();

    function _initialize()
    {
        $this->tablePrefix = C('DB_PREFIX');
    }

    /**
     * 检测发红包
     *
     * @param $uid
     * @param $sessionid 群聊的id
     * @param $score
     * @param $quantity
     * @param $type 1口令红包
     * @param $content
     * @return array
     */
    public function checkSend($uid,$sessionid,$score,$quantity,$type,$content){
        if(empty($score)){
            return array('status'=>1,'msg'=>'红包金额不能为空');
        }
        if(empty($quantity)){
            return array('status'=>2,'msg'=>'红包数量不能为空');
        }
        if(empty($type)){
            $type=1;
        }
        if($type==1 && empty($content)){
            return array('status'=>3,'msg'=>'红包口令不能为空');
        }
        $result=M('session')->where('id='.$sessionid)->find();

        if(empty($result)){
            return array('status'=>4,'msg'=>'群聊不存在');
        }
        if($result['status']==0){
            return array('status'=>5,'msg'=>'群聊未通过审核');
        }
//        if($result['min_score']>$score){
//            return array('status'=>6,'msg'=>'红包不能低于'.$result['min_score'].'元');
//        }
        $result_user=M('user')->where('uid='.$uid)->find();

        if($result_user['score']<$score){
            return array('status'=>7,'msg'=>'您的余额不足，请充值');
        }

        $result_session_user=M('session_user')->where('sessionid='.$sessionid)->select();
        if(count($result_session_user)<$quantity){
            return array('status'=>8,'msg'=>'红包数量不能超过'.count($result_session_user));
        }
        $max_quantity=$score * 100;
        if($max_quantity<$quantity){
            return array('status'=>9,'msg'=>'红包数量最多为'.$max_quantity.'个');
        }
        return array('status'=>0,'msg'=>'ok');
    }

    /**
     * 发红包
     * @param $uid 发红包人的uid
     * @param sessionid 群聊的sessionid
     * @param score 红包金额
     * @param quantity 红包个数
     * @param content 红包内容
     * @param type  1口令红包 2拼手气红包
     */
    public function sendRedbag($uid){
        $sessionid=I('sessionid');
        $score=I('score');
        $quantity=I('quantity');
        $content=I('content');
        $type=I('type');
        if(empty($type)){
            $type=1;//口令红包
        }
        $info=$this::checkSend($uid,$sessionid,$score,$quantity,$type,$content);
        if($info['status']!=0){
            return showData(new \stdClass(),$info['msg'],$info['status']);
        }else{
            $data['uid']=$uid;
            $data['score']=$score;
            $data['type']=$type;
            $data['score']=$score;
            $data['sessionid']=$sessionid;
            $data['give_score']=0;
            $data['quantity']=$quantity;
            $data['keywords']=$content;
            $data['update_time']=NOW_TIME;
            $data['create_time']=NOW_TIME;
            $data['deadline']=NOW_TIME + 86400;//红包过期时间为1天
            $redbag_id=M('redbag')->add($data);
            if($redbag_id){
                M('user')->where('uid='.$uid)->setDec('score',$score);//减少发红包用户的积分
                $tradeModel=new TradeModel();
                $tradeModel::add($uid,0,$score,$type==1?1:3);
                return showData(array('uid'=>$uid,'redbag_id'=>$redbag_id));
            }else{
                return showData(new \stdClass(),'红包发送失败',9);
            }
        }
    }

    /**
     * 查看红包领取详情
     * @param $uid
     * @param $redbag_id
     */
    public function catRedbag($uid){
        $redbag_id=I('redbag_id');
        $data=array();
        $result=M('redbag')->where('id='.$redbag_id)->find();
        if(empty($result)){
            return showData(new \stdClass(),'红包不存在',1);
        }
        $sendUResult=M('user')->where(array('uid'=>$result['uid']))->find();
        $data['uid']=$sendUResult['uid'];//发红包用户id
        $data['nickname']=$sendUResult['nickname'];//发红包用户昵称
        $data['headsmall']=$sendUResult['headsmall'];//发红包头像
        $data['score']=$result['score'];//红包共1元
        $data['give_score']=$result['give_score'];//已领取1元
        $data['quantity']=$result['quantity'];//共5份
        $data['keywords']=$result['keywords'];
        $data['type']=$result['type'];//红包类型1 口令，2拼手气
        $result['type']==1?$data['type_text']='令':$data['type_text']='拼';
        $myRedbagResult=M('redbag_detail')->where(array('redbag_id'=>$redbag_id,'uid'=>$uid))->find();
        if(empty($myRedbagResult)){
            $data['is_recieve']=0;
            $data['myscore']="0";
        }else{
            $data['is_recieve']=1;
            $data['myscore']=$myRedbagResult['score'];
        }
        if($result['score']==$result['give_score']){
            $data['is_grab']=1;//已领完
        }else{
            $data['is_grab']=2;//未领完
        }
        $redbag_list=M('redbag_detail')->where(array('redbag_id'=>$redbag_id))->select();
        $data['receive']=count($redbag_list);//已领取的数量
        $tempArr=array();
        foreach ($redbag_list as $k=>$v){
            $u_result=M('user')->where('uid='.$v['uid'])->find();
            $tempArr[$k]['uid']=$u_result['uid'];
            $tempArr[$k]['headsmall']=$u_result['headsmall'];
            $tempArr[$k]['nickname']=$u_result['nickname'];
            $tempArr[$k]['score']=$v['score'];
            $tempArr[$k]['receive_time']=$v['create_time'];
            //我
            if($uid==$v['uid']){
                $tempArr[$k]['its_me']=1;//是我
            }else{
                $tempArr[$k]['its_me']=0;
            }
            if($data['is_grab']==1){//已领完
                $max_score=  M('redbag_detail')->where('redbag_id='.$v['redbag_id'])->max('score');
                if($max_score==$v['score']){
                    $tempArr[$k]['is_max']=1;
                }else{
                    $tempArr[$k]['is_max']=0;
                }
            }else{//未领完
                $tempArr[$k]['is_max']=0;
            }
        }
        $data['list']=$tempArr;
        return showData($data);
    }


    /**
     * 检查抢红包
     * @param $uid
     * @param $type
     * @param $fuid
     * @param $redbag_id
     * @param $content
     */
    public function checkGrab($uid,$type,$fuid,$redbag_id,$content,$sessionid){
        if(empty($uid) || empty($type) || empty($fuid) || empty($redbag_id) || empty($content) || empty($sessionid)){
            return array('status'=>1,'msg'=>'参数不完整');
        }
        if($type==1 ){
            if(empty($content)){
                return array('status'=>2,'msg'=>'口令不能为空');
            }
            $redbagResult=M('redbag')->where(array('id'=>$redbag_id))->find();
            if($content != $redbagResult['keywords']){
                return array('status'=>7,'msg'=>'口令不正确');
            }
        }

        $result=M('redbag')->where('id='.$redbag_id)->find();
        if($result['score']==$result['give_score']){
            return array('status'=>3,'msg'=>'手慢了，红包派完了');
        }

        $map1['redbag_id']=array('eq',$redbag_id);
        $map1['uid']=array('eq',$uid);
        if(M('redbag_detail')->where($map1)->find()){
            return array('status'=>4,'msg'=>'你已经领过该红包');
        }
        $map2['id']=array('eq',$redbag_id);
        $map2['deadline']=array('lt',NOW_TIME);
        if(M('redbag')->where($map2)->find()){
            return array('status'=>5,'msg'=>'红包已过期');
        }

        $user_score=M('user')->where(array('uid'=>$uid))->getField('score');
        $session_min_score=M('session')->where(array('id'=>$sessionid))->getField('min_score');

        if($session_min_score>$user_score){
            return array('status'=>6,'msg'=>'本群最低参与金额为'.$session_min_score.'元，请充值');
        }


        return array('status'=>0,'msg'=>'ok');
    }
    /**
     * 抢红包
     * @param redbag_id 红包id
     * @param uid 抢红包的用户id
     * @param fuid 发红包的用户id
     * @param sessionid 群聊的id
     * @param type 红包类型 1 口令 2 普通
     * @param content 红包口令
     */
    public function grabRedbag($uid){
        $type=I('type');
        $fuid=I('fuid');
        $redbag_id=I('redbag_id');
        $content=I('content');
        $sessionid=I('sessionid');
        $info=$this::checkGrab($uid,$type,$fuid,$redbag_id,$content,$sessionid);
        if ($info['status'] !=0){
            return showData(new \stdClass(),$info['msg'],$info['status']);
        }
        $map['redbag_id']=array('eq',$redbag_id);

        $hasGrab=M('redbag_detail')->where($map)->count();//已经领的数量
        $quantity=M('redbag')->where('id='.$redbag_id)->getField('quantity');//总数量
        $de_quantity=$quantity-$hasGrab;//剩下的数量
        $score=M('redbag')->where('id='.$redbag_id)->getField('score')-M('redbag')->where('id='.$redbag_id)->getField('give_score');//剩下的钱

        if($score>0 && $de_quantity!=1){//剩下的数量2个以上
            $sendScore=getRandScore($score,$de_quantity,1)[0];
        }elseif ($score>0 && ($de_quantity==1)){//剩下的数量只有一个
            $sendScore=$score;
            //并且对群主发送红包结果通知，且将红包状态设为0

        }else{//不剩下了
            return showData(new \stdClass(),'没有可以领取的红包啦',3);
        }
        $data['score']=$sendScore;
        $data['redbag_id']=$redbag_id;
        $data['uid']=$uid;
        $data['fuid']=$fuid;
        $data['type']=$type;
        $data['create_time']=NOW_TIME;
        $result=M('redbag_detail')->add($data);
        if($result){
            M('redbag')->where('id='.$redbag_id)->setInc('give_score',$sendScore);
            M('redbag')->where('id='.$redbag_id)->setField('update_time',NOW_TIME);
            M('user')->where('uid='.$uid)->setInc('score',$sendScore);

            $tradeModel=new TradeModel();
            $tradeModel::add($uid,$fuid,$sendScore,$type==1?2:4);


            /**
             * 以下是推送
             * 给群主发送推送消息
             * 推送类型
             **/
            if($de_quantity==1){//只剩下一个包，把红包领取详情+结果发出去
                $push = new Push;
                $fResult=$push::sendRedbagNotice($uid,$sessionid,2,$redbag_id);
                $sResult=$push::sendRedbagResult($redbag_id);
                //把红包设为已推送
                M('redbag')->where(array('id'=>$redbag_id))->setField('is_push',1);
                if (!$fResult || ! $sResult){

                }
            }else{//发送红包领取的详情
                $push = new Push;
                $fResult=$push::sendRedbagNotice($uid,$sessionid,2,$redbag_id);
                if(!$fResult){

                }
            }

            return showData(new \stdClass(),'ok',0);
        }else{
            return showData(new \stdClass(),'异常错误，请检查网络连接',6);
        }
    }

    /**
     * 极光推送,个人或者群聊[个人sessionid 为空,群聊ruid为空]
     * @param ruid [接收推送消息的用户]指个人
     * @param sessionid [会话id] 指群聊
     */
    public function sendNotify($uid,$ruid,$sessionid){

        if($sessionid){
            $result=M('session_user')->where('sessionid='.$sessionid.' and uid != '.$uid)->select();
            $tempArr=array();
            foreach($result as $key=>$val){
                $tempArr[]=$val['uid'];
            }
            $ruid=implode(',',$tempArr);
        }

        $ruid=explode(',',$ruid);
        $app_key=JPUSH_KEY;
        $master_secret=JPUSH_SECRET;
        $client = new JPush($app_key, $master_secret);
        $push_payload = $client->push()
            ->setPlatform('all')
            ->addTag($ruid)
            ->iosNotification('你收到了一条新消息',array('extras'=>array('sessionid'=>$sessionid)) );
        try {
            $response = $push_payload->send();
        }catch (\JPush\Exceptions\APIConnectionException $e) {
            return showData(new \stdClass(), 'Jpush error',1);//print_r($e);
        } catch (\JPush\Exceptions\APIRequestException $e) {
            return showData(new \stdClass(), 'Jpush error',1);
        }
        return showData(new \stdClass(), '推送成功');
    }

    /**
     * 发送红包记录，按照年
     * @param $year 2016
     * @param $uid 用户id
     * @return array
     */
    public function sendRedbagList($uid){
        $userModel=new UserModel();
        $user_result= $userModel->getUserName($uid);
        $data['uid']=$user_result['uid'];
        $data['name']=$user_result['name'];
        $data['headsmall']=$user_result['headsmall'];

        $year=I('year');
        $starttime=strtotime($year.'-01-01 00:00:00');
        $endtime=strtotime($year.'-12-31 00:00:00');
        $map['create_time']=array('between',array($starttime,$endtime));
        $map['uid']=array('eq',$uid);
        $map['give_score']=array('neq',0);

        $result=M('redbag')->field('give_score,uid,quantity,create_time,id,type')->where($map)->order('create_time desc')->select();
        if(empty($result)){
            return showData(new \stdClass(),'你还没有发过红包！',1);
        }
        $data['count']=M('redbag')->where($map)->count();
        $data['score_sum']=M('redbag')->where($map)->sum('give_score');

        foreach ($result as $k=>$v){
            $call_back[$k]['give_score']=$v['give_score'];
            $call_back[$k]['quantity']=$v['quantity'];
            $redbag_map['fuid']=array('eq',$v['uid']);
            $redbag_map['redbag_id']=array('eq',$v['id']);
            $call_back[$k]['hasGrab']=M('redbag_detail')->where($redbag_map)->count();
            $v['type']==1?$call_back[$k]['type_text']='口令红包':$call_back[$k]['type_text']='拼手气红包';
            $call_back[$k]['time']=date('m-d',$v['create_time']);
        }
        $data['list']=$call_back;
        return showData($data);
    }

    /**
     * 领红包记录
     * @param $year
     * @param $uid
     * @return array
     */
    public function grabRedbagList($uid){
        $userModel=new UserModel();
        $user_result= $userModel->getUserName($uid);
        $data['uid']=$user_result['uid'];
        $data['name']=$user_result['name'];
        $data['headsmall']=$user_result['headsmall'];

        $year=I('year');
        $starttime=strtotime($year.'-01-01 00:00:00');
        $endtime=strtotime($year.'-12-31 00:00:00');
        $map['create_time']=array('between',array($starttime,$endtime));
        $map['uid']=$uid;
        $data['count']=M('redbag_detail')->where($map)->count();
        $data['score_sum']=M('redbag_detail')->where($map)->sum('score');

        $result=M('redbag_detail')->where($map)->order('create_time desc')->select();
        if(empty($result)){
            return showData(new \stdClass(),'你还没有领过红包',1);
        }
        $max=0;
        foreach ($result as $k=>$v){
            $call_back[$k]['name']=$userModel->getUserName($v['fuid'])['name'];
            $call_back[$k]['score']=$v['score'];
            $call_back[$k]['time']=date('m-d',$v['create_time']);
            $v['type']==1?$call_back[$k]['type_text']='令':$call_back[$k]['type_text']='拼';

            $max_score=  M('redbag_detail')->where('redbag_id='.$v['redbag_id'])->max('score');
            if($max_score==$v['score']){
                $max +=1;
                $call_back[$k]['is_max']=1;
            }else{
                $call_back[$k]['is_max']=0;
            }
        }
        $data['max']=$max;
        $data['list']=$call_back;
        return showData($data);
    }

    /**
     * 发送单人红包
     * @param $uid
     * @param $fuid
     * @param $type
     * @param $quantity
     * @param $score
     * @param $content
     * @return array
     */
    public function sendSingleRedbag($uid){
        $data=array();
        $fuid=I('fuid');
        $data['uid']=$uid;
        $data['type']=I('type');
        $data['quantity']=I('quantity');
        $data['score']=I('score');
        $data['keywords']=I('content');
        $data['create_time']=NOW_TIME;
        $data['update_time']=NOW_TIME;
        $data['deadline']=NOW_TIME + 86400;
        if(empty($data['score'])){
            return showData(new \stdClass(),'金额不能为空',1);
        }
        if($data['quanatity'] > 1){
            return showData(new \stdClass(),'数量不能大于1',2);
        }

        if($data['type']==1){
            if(empty($data['keywords'])){
                return showData(new \stdClass(),'口令不能为空',3);
            }
        }
        $myscore=M('user')->where(array('uid'=>$uid))->getField('score');
        if($myscore < $data['score']){
            return showData(new \stdClass(),'你的余额不足，请充值',4);
        }
        $result=$this->add($data);
        if($result){
            M('user')->where(array('uid'=>$uid))->setDec('score',$data['score']);
            $tradeModel=new TradeModel();
            $tradeModel->add($uid,$fuid,$data['score'],$data['type']==1?1:3);
            return showData(array('uid'=>$uid,'redbag_id'=>$result));
        }else{
            return showData(new \stdClass(),'发送失败，请检查网络连接',5);
        }
    }

    /**
     * 抢单人发的红包
     * @param $uid
     * @param $fuid
     * @param $redbag_id
     * @param $content
     * @return array
     */
    public function grabSingleRedbag($uid){
        $type=I('type');
        $fuid=I('fuid');
        $redbag_id=I('redbag_id');
        $content=I('content');

        $result=M('redbag_detail')->where(array('redbag_id'=>$redbag_id))->find();
        if(!empty($result))
            return showData(new \stdClass(),'你已经抢过了',1);

        if($uid == $fuid)
            return showData(new \stdClass(),'不能领取自己发的红包',2);

        if($type==1){
            if(empty($content)){
                return showData(new \stdClass(),'口令不能为空',3);
            }
        }
        $sendScore=M('redbag')->where(array('id'=>$redbag_id))->getField('score');
        $data['score']=$sendScore;
        $data['redbag_id']=$redbag_id;
        $data['uid']=$uid;
        $data['fuid']=$fuid;
        $data['type']=$type;
        $data['create_time']=NOW_TIME;
        $result_redbag_detail=M('redbag_detail')->add($data);
        if($result_redbag_detail){
            M('redbag')->where('id='.$redbag_id)->setInc('give_score',$sendScore);
            M('redbag')->where('id='.$redbag_id)->setField(array('update_time'=>NOW_TIME,'status'=>0));
            M('user')->where('uid='.$uid)->setInc('score',$sendScore);

            $tradeModel=new TradeModel();
            $tradeModel::add($uid,$fuid,$sendScore,$type==1?2:4);

            return showData(new \stdClass(),'ok',0);
        }else{
            return showData(new \stdClass(),'异常错误，请检查网络连接',4);
        }
    }
}